//
//  SNSMainViewController.m
//  IntroductionApp
//
//  Created by brave on 11/08/01.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SNSMainViewController.h"
#import "timeLineCell.h"

#import "MGTwitterEngine.h"

#import "IntroAPPUtil.h"
#import "IntroductionAppAppDelegate.h"


@implementation SNSMainViewController

@synthesize twitTabel = _twitTabel;
@synthesize picImage = _picImage;
@synthesize accountLabel = _accountLabel;
@synthesize commentLabel = _commentLabel;

@synthesize SAEngine = _SAEngine;
@synthesize TwitEngine = _TwitEngine;
@synthesize timeLineDicAry = _timeLineDicAry;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [ _twitTabel release ];
    [ _picImage release ];
    [ _accountLabel release ];
    [ _commentLabel release ];
    
    [ _SAEngine release ];
    [ _TwitEngine release ];
    [ _timeLineDicAry release ];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

/* ====================================================================================== */
#pragma mark - View lifecycle
/* ====================================================================================== */

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (self.SAEngine) return;
	self.SAEngine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
	self.SAEngine.consumerKey = TWITTER_CONSUMERKEY;
	self.SAEngine.consumerSecret = TWITTER_CONSUMER_SECRET;
    
    self.twitTabel.delegate = self;
    self.twitTabel.dataSource = self;
    self.timeLineDicAry = [[ NSMutableArray alloc ]init];
    
    // ユーザー情報取得
    [ self.SAEngine getUserInformationFor:TWITTER_USER_NAME ];
}

-(void)viewWillAppear:(BOOL)animated{
    [ super viewWillAppear:animated ];
    
    // タイムライン取得
    [ self.SAEngine getUserTimelineFor:TWITTER_USER_NAME sinceID:0 startingAtPage:20 count:20 ];
}

-(void)viewDidAppear:(BOOL)animated{
    [ super viewDidAppear:animated ];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    _twitTabel = nil;
    _picImage = nil;
    _accountLabel = nil;
    _commentLabel = nil;
    _timeLineDicAry = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

/* ====================================================================================== */
#pragma mark - Thread method
/* ====================================================================================== */

// timeLineCellの中身を作成
-(void)createTimeLineCell:(NSArray*)argAry{
    NSAutoreleasePool *pool = [[ NSAutoreleasePool alloc ] init];
    
    timeLineCell *cell      = [ argAry objectAtIndex:0 ];
    NSIndexPath *indexpath  = [ argAry objectAtIndex:1 ];
    
    // cell作成処理
    NSDictionary *dic = [self.timeLineDicAry objectAtIndex:indexpath.row];
    
    NSLog(@"dic = %@",[ dic description ]);
        
    // set tweet
    NSString *tweet = [dic objectForKey:@"text"];
    float ff = [ IntroAPPUtil textHeight:tweet fontSize:13 labelWidth:cell.accountLabel.frame.size.width ];
    [ cell performSelectorOnMainThread:@selector(setLabelHeight:) withObject:[ NSNumber numberWithFloat:ff ] waitUntilDone:YES ];
    [ cell.accountLabel performSelectorOnMainThread:@selector(setText:) withObject:tweet waitUntilDone:YES];
    
    // Setimage
    NSString * URLStr = [ [ dic objectForKey:@"user"] objectForKey:@"profile_image_url"];
    NSURL *url = [NSURL URLWithString:URLStr];
    NSData * data = [NSData dataWithContentsOfURL:url];
    UIImage *tImage = [[UIImage alloc]initWithData:data];
    [ cell.twitterImage performSelectorOnMainThread:@selector(setImage:) withObject:tImage waitUntilDone:YES ];
    [ tImage release ];
    
    [ pool release ];
}

// 処理が重いので、別で処理
-(void)setTimeStamp:(NSArray*)arys{
    NSAutoreleasePool *pool = [[ NSAutoreleasePool alloc ]init];
    
    timeLineCell *cell      = [ arys objectAtIndex:0 ];
    NSIndexPath *indexpath  = [ arys objectAtIndex:1 ];
    
    // cell作成処理
    NSDictionary *dic = [self.timeLineDicAry objectAtIndex:indexpath.row];    
    // set Time (Bug)
    NSString *ttt = [dic objectForKey:@"created_at"];
    NSDate *tweetData = [ IntroAPPUtil dateFromCreatedAtDateString:ttt ];
    NSString *timeStr = [ IntroAPPUtil NSDateToFormatString:tweetData ];
    [ cell.timeLabel performSelectorOnMainThread:@selector(setText:) withObject:timeStr waitUntilDone:NO];
    
    [ pool release ];
}


/* ====================================================================================== */
#pragma mark - Table view data source
/* ====================================================================================== */

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    // Return the number of rows in the section.
    return [ self.timeLineDicAry count ];
}

// 動的にcellの高さを計算する
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"timeLineCell";
    
    timeLineCell *cell = (timeLineCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[ NSBundle mainBundle ] loadNibNamed:@"timeLineCell" 
                                                owner:self
                                              options:nil]lastObject];
    }
    
    // BackGround
    NSArray *argumentAry = [[ NSArray alloc ]initWithObjects:cell,indexPath, nil];
    [ self performSelectorInBackground:@selector(createTimeLineCell:) withObject:argumentAry ];
    [ self performSelectorInBackground:@selector(setTimeStamp:) withObject:argumentAry ];
    [ argumentAry release ];
    
    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/* ====================================================================================== */
#pragma mark - Table view delegate
/* ====================================================================================== */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}

/* ====================================================================================== */
#pragma mark - Twitter
/* ====================================================================================== */



/* ====================================================================================== */
#pragma mark - MGTwitterEngineDelegate
/* ====================================================================================== */

//　ユーザー情報取得成功
- (void)userInfoReceived:(NSArray *)userInfo forRequest:(NSString *)connectionIdentifier{
    
    for ( NSDictionary *dic in userInfo) {
        
        // set
        self.accountLabel.text = [ NSString stringWithFormat:@"@%@",TWITTER_USER_NAME ];
        self.commentLabel.text = [ dic objectForKey:@"description"];
        
        // Setimage
        NSURL *url = [NSURL URLWithString:[ dic objectForKey:@"profile_image_url"]];
        NSData * data = [NSData dataWithContentsOfURL:url];
        self.picImage.image = [[UIImage alloc]initWithData:data];
    }
}

// タイムラインの取得成功
- (void)statusesReceived:(NSArray *)statuses
              forRequest:(NSString *)connectionIdentifier{
    for ( NSDictionary *dic in statuses) {
        // 各つぶやき格納
        [self.timeLineDicAry addObject:dic];
    }
    [ self.twitTabel reloadData ];
}

// タイムライン取得失敗
- (void)requestFailed:(NSString *)connectionIdentifier withError:(NSError *)error {

    NSLog(@"Request failed for connectionIdentifier = %@, error = %@ (%@)", 
          connectionIdentifier, 
          [error localizedDescription], 
          [error userInfo]);
}



@end
